#coding:utf8
from django.shortcuts import redirect, render, HttpResponse
from importlib import import_module
from django.conf import settings
import json
import logging
import functools
from core.lib.fun import ApiResponseJson, parseString
import urllib.parse

logger = logging.getLogger("api")

def api_load_session(request):
    sessionKey = request.GET.get('token', '').strip()
    if sessionKey:
        engine = import_module(settings.SESSION_ENGINE)
        request.session = engine.SessionStore(sessionKey)

    return request.session

#平台
def require_admin(input_function):
    @functools.wraps(input_function)
    def wrapper(*args, **kwargs):
        request = args[0]

        if request.user.is_authenticated:
            try:
                requestBody = parseString(request.body)
            except:
                requestBody = ""

            logInfo = {
                'method': request.method,
                'user_id': request.user.id,
                'url': "%s?%s"%(request.META.get('PATH_INFO', ''), request.META.get('QUERY_STRING', '')),
                'request_body': requestBody,
            }
            logger.info(json.dumps(logInfo))

            return input_function(*args, **kwargs)
        else:
            return redirect('/login?returnUrl=%s'% urllib.parse.quote(request.get_full_path()))

    return wrapper

